<?php

namespace App\Domains;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 管理员domain
 */
class AdminDomain
{

  /**
   * 获取指定用户信息
   * @param int $uid
   * @return object|null
   */
  public static function getAdminInfo(int $uid): ?object
  {
    $selectFields = [
      // "aa.username",
      "aa.name",
      "aa.adminRoleId",
      "aa.avatar",
      "aa.isSuper",
      "aa.lastLoginTime",
      "sd.deptName as departmentName",
      "ar.roleName",
    ];
    $adminInfo = DB::table("admin as aa")
      ->leftJoin("admin_department as sd", "sd.id", "=", "aa.adminDepartmentId")
      ->leftJoin("admin_role as ar", "ar.id", "=", "aa.adminRoleId")
      ->where("aa.adminId", $uid)
      ->where("aa.status", "=", 1)
      ->select($selectFields)
      ->first();
    return $adminInfo;
  }

  /**
   * 获取指定用户信息带缓存
   * @param int $uid
   * @param int $cacheSeconds
   * @return object|null
   */
  public static function getAdminInfoCache(int $uid, int $cacheSeconds = 0): ?object
  {
    $cacheKey = "adminer_{$uid}";
    $userInfo = Cache::get($cacheKey);
    if (null === $userInfo) {//未缓存
      $userInfo = self::getAdminInfo($uid);
      if ($userInfo) {// 有数据则缓存
        $cacheSeconds > 0 ? Cache::put($cacheKey, $userInfo, $cacheSeconds) : Cache::forever($cacheKey, $userInfo);
      }
    }
    return $userInfo;
  }
}
